<template>
  <div class="content-div">
    <el-tree ref="permTree"
             class="tree-div"
             :props="permTreeDataProps"
             node-key="id"
             :data = "permsData"
             show-checkbox
             :default-expand-all="true"
             :check-strictly="true"
             :default-checked-keys="bindedPermids"
             @check-change="checkBindPerms">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>&nbsp;<span class="text-danger">{{ data.available===0?'[禁用]':'' }}</span>
        </span>
    </el-tree>
    <div class="btn-bar">
      <el-button type="text" size="mini" @click="checkAll()">全选</el-button>
      <el-button type="text" size="mini" @click="checkAll(false)">取消全选</el-button>
    </div>
  </div>
</template>

<script>
  export default {
    name: "PermissionTree",
    model: {
      prop: 'mval',
      event: 'modelValue'
    },
    props: ['mval', 'resources'],
    watch: {
      mval: {
        handler() {
          this.bindedPermids = this.mval;
        },
        immediate: true,
        deep: true
      }
    },
    data() {
      return {
        permTreeDataProps: {
          label: 'text',
          children: 'children'
        },
        permsData: [],
        bindedPermids: [],
        allIds: []
      }
    },
    mounted: function() {
      this.api.post('/bucket-system/system/resources/all', {})
        .then((data) => {
          this.parseDatas(data.data);

          this.permsData = data.data;
        });
    },
    methods: {
      checkBindPerms: function(data, checked, indeterminate){
        this.$emit('modelValue', this.$refs.permTree.getCheckedKeys());
      },
      parseDatas: function(list){
        for(let i=0; i<list.length; i++){
          this.allIds.push(list[i].id);
          this.parseDatas(list[i].children);
        }
      },
      checkAll: function(uncheck){
        if(uncheck===false)
          this.$refs.permTree.setCheckedKeys([]);
        else
          this.$refs.permTree.setCheckedKeys(this.allIds);
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.content-div{
  position: relative;
  height: -webkit-fill-available;
  .tree-div{
    overflow: auto;
    position: absolute;
    bottom: 30px;
    top: 0;
    width: 100%;
  }
  .btn-bar{
    position: absolute;
    width: 100%;
    height: 30px;
    bottom: 0;
    background-color: white;
    padding-left: 5px;
  }
}
</style>
